﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace XTools.App_Code
{
    public class StrHelper
    {
        /// <summary>
        /// 获取域长度
        /// </summary>
        /// <param name="start_position">起始位置</param>
        /// <returns>域长度</returns>
        public static int GetCellLength(int start_position)
        {
            return start_position / 64 + 1;
        }

        /// <summary>
        /// 如果字符串长度小于指定长度，即返回该长度的字符串
        /// </summary>
        /// <param name="str">待处理字符串</param>
        /// <param name="length">指定长度</param>
        /// <returns>处理后字符串</returns>
        public static string GetStrByLength(string str, int length)
        {
            while (str.Length < length)
            {
                str = "0" + str;
            }
            return str;
        }

        /// <summary>
        /// 重写文件
        /// </summary>
        public static void reWrite(string fileName, string msg)
        {
            FileStream fs = null;
            StreamWriter sw = null;
            try
            {
                fileName = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + fileName;
                fs = new FileStream(fileName, FileMode.Create, FileAccess.Write);
                sw = new StreamWriter(fs, System.Text.Encoding.UTF8);
                sw.Write(msg);
                sw.Flush();
            }
            catch (Exception) { }
            finally
            {
                if (sw != null)
                {
                    sw.Close();
                }
                if (fs != null)
                {
                    fs.Close();
                }
            }
        }

        /// <summary>
        /// 追加文件
        /// </summary>
        public static void write(string fileName, string msg)
        {
            FileStream fs = null;
            StreamWriter sw = null;
            try
            {
                fileName = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + fileName;
                fs = new FileStream(fileName, FileMode.Append, FileAccess.Write);
                sw = new StreamWriter(fs);
                sw.Write(msg);
                sw.Flush();
            }
            catch (Exception) { }
            finally
            {
                if (sw != null)
                {
                    sw.Close();
                }
                if (fs != null)
                {
                    fs.Close();
                }
            }
        }
    }
}